<template>
  <el-form ref="ruleFormRef" :model="form" label-width="80" :rules="rules">
    <el-form-item label="用户名" prop="name">
      <el-input v-model="form.name" clearable placeholder="请输入用户名" class="constWidth" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="form.password" clearable type="password" show-password placeholder="请输入密码" class="constWidth" />
    </el-form-item>
    <el-form-item v-if="loginTtype==='inject'" label="确认密码" prop="passwordRe">
      <el-input v-model="form.passwordRe" clearable type="password" show-password placeholder="请输入密码" class="constWidth" />
    </el-form-item>
    <el-form-item class="button-area">
      <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
      <el-button @click="resetForm(ruleFormRef)">取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script lang="ts">
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { loginService } from '@/service/index'
import { Encrypt } from '@/tools/secret'
import { userStore } from '@/stores/user'
import { useRouter } from 'vue-router' // eslint-disable-line
interface RuleForm {
  name: string
  password: string,
  passwordRe: string
}
export default {
  props: ['type'],
  setup(props) {
    const loginTtype = props.type
    const form = reactive<RuleForm>({} as RuleForm)
    const validatePass1 = (rule: any, value: any, callback: any) => {
      if (loginTtype === 'login') {
        callback()
      } else {
        if (!form.name) {
          callback()
        } else {
          checkName(form.name).then((res) => {
            if (res) {
              callback()
            } else {
              callback(new Error('用户名已存在!'))
            }
          })
        }
      }
    }
    const validatePass2 = (rule: any, value: any, callback: any) => {
      if (value !== form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    const rules = reactive<FormRules<RuleForm>>({
      name: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { validator: validatePass1, trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ],
      passwordRe: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        { validator: validatePass2, trigger: 'blur' }
      ]
    })
    const ruleFormRef = ref<FormInstance>()
    const store = userStore()
    const router = useRouter()
    const submitForm = async(formEl: FormInstance | undefined) => {
      if (!formEl) return
      await formEl.validate((valid, fields) => {
        if (valid) {
          const mid:RuleForm = { name: form.name } as RuleForm
          const secStr = Encrypt(form.password)
          mid.password = secStr
          if (form.passwordRe) {
            mid.passwordRe = secStr
          }
          loginService.post('/login', mid).then((res: any) => {
            if (res.code === 200) {
              ElMessage({
                message: res.data,
                type: 'success'
              })
              // TODO 存token,跳转主页
              const avatar = res.avatar ?? ''
              // @ts-ignore
              store.setUserInfo(form.name, res.token, res.role || 'common', avatar)
              router.push('/table')
            } else {
              ElMessage({
                message: '用户名或密码错误',
                type: 'error'
              })
            }
          }).catch((err:any) => {
            ElMessage.error(err.message)
          })
        } else {
          console.log('error submit!', fields)
        }
      })
    }
    const resetForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return
      formEl.resetFields()
    }
    const checkName = (name: string) => {
      return new Promise((resolve) => {
        loginService.get(`/checkname/${name}`).then((res:any) => {
          resolve(res.data)
        })
      })
    }
    return { form, rules, ruleFormRef, loginTtype, submitForm, resetForm, checkName }
  }
}

</script>
<style lang="less" scoped>
 .constWidth{
  width:250px;
 }
.el-form{
  padding: 20px 20px 0;
  .button-area{
    ::v-deep(.el-form-item__content){
    justify-content: center!important;
   }
  }
 }
</style>
